package cn.kimoon.dau_android;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import cn.kimoon.dau_android.API.ApiDAU;
import cn.kimoon.dau_android.API.AppClient;
import cn.kimoon.dau_android.Model.ModelEngineRoom;
import cn.kimoon.dau_android.Model.ModelEngineRoomItem;
import cn.kimoon.dau_android.pullableview.PullToRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiangdong on 2016/12/9.
 */

public class SearchActivity extends AppCompatActivity implements View.OnClickListener,
        PullToRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {
    public static final int kPageSize = 15;    // 请求数据每一页的数量

    private ImageButton clearButton;
    private EditText editText;
    private PullToRefreshLayout pullToRefreshLayout;

    private ModelEngineRoom model;
    private EngineRoomAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        initLogicData();
        initSubViews();
    }

    // 初始化逻辑数据
    private void initLogicData() {
        model = new ModelEngineRoom();
    }

    private void initSubViews() {
        editText = (EditText) findViewById(R.id.search_edit_text);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() < 1) {
                    clearButton.setVisibility(View.INVISIBLE);
                } else {
                    clearButton.setVisibility(View.VISIBLE);
                }

                requestEngineRoomSearch(pullToRefreshLayout, true);
            }
        });

        clearButton = (ImageButton) findViewById(R.id.search_clear_button);
        clearButton.setOnClickListener(this);
        clearButton.setVisibility(View.INVISIBLE);

        Button cancelButton = (Button) findViewById(R.id.search_cancel_btn);
        cancelButton.setOnClickListener(this);

        // 刷新控件
        pullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.search_refresh_view);
        pullToRefreshLayout.setOnRefreshListener(this);

        ListView listView = (ListView) findViewById(R.id.search_list_view);
        adapter = new EngineRoomAdapter(null, this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

    // ListView点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ModelEngineRoomItem item = model.result.get(position);

        Intent intent = new Intent(this, MonitorDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("collectorId", item.id);
        bundle.putString("collectorName", item.name);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    // 按键点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_clear_button:
                clearBtnTapped();
                break;
            case R.id.search_cancel_btn:
                cancelBtnTapped();
                break;
        }
    }

    private void clearBtnTapped() {
        editText.setText("");
    }

    private void cancelBtnTapped() {
        finish();
    }

    // 刷新控件
    @Override
    public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
        requestEngineRoomSearch(pullToRefreshLayout, true);
    }

    @Override
    public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
        requestEngineRoomSearch(pullToRefreshLayout, false);
    }

    // 网络请求
    private void requestEngineRoomSearch(final PullToRefreshLayout pullToRefreshLayout , final boolean isHeader) {
        String string = editText.getText().toString();
        if (string.length() < 1) {
            refreshLayoutEndRefresh(pullToRefreshLayout, isHeader);
            return;
        }

        Map<String, String> parameters = new HashMap<>();
        int page = isHeader ? 0 : model.result.size();
        parameters.put("page", Integer.toString(page));
        parameters.put("size", Integer.toString(kPageSize));
        parameters.put("keyword", string);

        ApiDAU apiDAU = AppClient.retrofit().create(ApiDAU.class);
        Call<ModelEngineRoom> call = apiDAU.apiCollectorList(parameters);
        call.enqueue(new Callback<ModelEngineRoom>() {
            @Override
            public void onResponse(Call<ModelEngineRoom> call, Response<ModelEngineRoom> response) {
                refreshLayoutEndRefresh(pullToRefreshLayout, isHeader);
                if (response.body() != null && response.body().errCode == 200) {
                    if (isHeader) {
                        model = response.body();
                    } else {
                        model.addMoreData(response.body());
                    }
                    adapter.setData(model.result);
                } else {
                    String msg = (response.body() == null ? response.message() : response.body().msg);
                    Toast.makeText(SearchActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ModelEngineRoom> call, Throwable t) {
                refreshLayoutEndRefresh(pullToRefreshLayout, isHeader);
                Toast.makeText(SearchActivity.this, R.string.internet_request_failed, Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 停止刷新
    private void refreshLayoutEndRefresh(final PullToRefreshLayout pullToRefreshLayout , boolean isHeader) {
        if (isHeader) {
            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
        } else  {
            pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        }
    }
}
